﻿using System;
using System.Collections.Generic;

namespace BizElements.Core
{
    /// <summary>FROM clause.</summary>
    public sealed class FromClause
    {
        internal FromClause(IDbTable firstTable, DbRelation[] orderedRelations, TableWithJoinMode[] orderedFromTablesIncludingFirstTable)
        {
            this.FromTable = firstTable;

            JoinClause[] joins = new JoinClause[orderedRelations.Length];
            for (int relationIdx = 0; relationIdx < orderedRelations.Length; relationIdx++)
            {
                int joinedTableIdx = relationIdx + 1;
                joins[relationIdx] = new JoinClause(orderedRelations[relationIdx], orderedFromTablesIncludingFirstTable[joinedTableIdx].Table, orderedFromTablesIncludingFirstTable[joinedTableIdx].JoinAsOuter);
            }

            this.Joins = joins;
            this.JoinCount = joins.Length;
        }

        /// <summary>FROM table.</summary>
        public IDbTable FromTable { get; private set; }
        /// <summary>JOIN clauses.</summary>
        public IEnumerable<JoinClause> Joins { get; private set; }
        /// <summary>Number of JOIN clauses.</summary>
        public int JoinCount { get; private set; }
    }

    /// <summary>JOIN clause.</summary>
    public sealed class JoinClause
    {
        internal JoinClause(DbRelation relation, IDbTable joinedTable, bool isLeftOuterJoin)
        {
            this.Relation = relation;
            this.JoinedTable = joinedTable;
            this.IsLeftOuterJoin = isLeftOuterJoin;
        }

        /// <summary>DB relation.</summary>
        public DbRelation Relation { get; private set; }
        
        /// <summary>Joined table.</summary>
        public IDbTable JoinedTable { get; private set; }

        /// <summary>Indicates whether this is a LEFT OUTER joint.</summary>
        public bool IsLeftOuterJoin { get; private set; }
    }
}